<?php
namespace Admin\Controller;
use Admin\Common\FileUtil;
/**
 * Class BuilderController
 * @package Admin\Controller
 */
class BuilderController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        load('@.builder');
    }

    /**
     * curd操作页面
     */
    public function index()
    {
        $this->assign('tableNameList', getTableNameList());
        $this->assign('moduleNameList', getModuleNameList());
        $this->display();
    }

    /**
     * 生成所有代码对应的文件
     */
    public function createAllFiles()
    {
        $tableNameList = I('selectTableName'); // 控制器列表
        $moduleName = I('moduleName'); // 模块名称
        $isCURD = I('isCURD'); // 是否CURD方法代码
        $isModel = I('isModel'); // 是否创建模型
        $extendsModuleName = I('extendsModuleName') ? I('extendsModuleName') : ''; // 继承模块
        $extendsClassName = I('extendsClassName'); // 继承类对象
        $this->assign('extendsModuleName', $extendsModuleName);
        $this->assign('extendsClassName', $extendsClassName);
        $methodList = getDirList(MODULE_PATH . TPH_TEMPLATE_PATH . TPH_CONTROLLER_PATH . TPH_METHOD_PATH, 'file');
        $prefix = C('DB_PREFIX');
        foreach ($tableNameList as $tableName) {
            $tableName = ltrim($tableName, $prefix);
            # 控制器
            $controllerStr = ""; // 定义控制器字符串
            if ($isCURD) {
                foreach ($methodList as $method) {
                    $controllerStr .= $this->getControllerCode(null, $method, $tableName, $moduleName) . "\r\n\r\n";
                }
            }
            $this->assign('allCode', $controllerStr);
            $controllerStr = $this->getControllerCode("Controller.html", null, $tableName, $moduleName);
            FileUtil::writeFile(getControllerPath($moduleName, $tableName), $controllerStr); //生成Controller文件
            # END-控制器

            # 模型
            if($isModel){
                $modelStr = $this->getModelCode("Model.html", $tableName, $moduleName);
                FileUtil::writeFile(getModelPath($moduleName, $tableName), $modelStr); //生成Controller文件
            }
            # END-模型

            # 视图
            // TODO: 先获取对应模块下的视图, 不存在则获取通用视图
            $indexViewStr = $this->getViewCode("index.html", $tableName);
            FileUtil::writeFile(getViewPath($moduleName, $tableName, 'index'), $indexViewStr);

            $addViewStr = $this->getViewCode("add.html", $tableName);
            FileUtil::writeFile(getViewPath($moduleName, $tableName, 'add'), $addViewStr);

            $editViewStr = $this->getViewCode("edit.html", $tableName);
            FileUtil::writeFile(getViewPath($moduleName, $tableName, 'edit'), $editViewStr);
            # END-视图
        }

        $this->mtReturn(200, "生成完成!", $_REQUEST['navTabId'], false);
//        $this->success('生成完成!');
    }


    /**
     * 获取控制器代码
     * @param $controllerFileName
     * @param null $methodFileName
     * @param null $tableName
     * @return string
     */
    public function getControllerCode($controllerFileName, $methodFileName = null, $tableName = null, $moduleName=null)
    {
        $this->getCodeInit();
        $tableName = $tableName ? $tableName : I('table');
        $isPage = I('isPage');
        $this->assign('tableName', columNameToVarName($tableName));
        $this->assign('moduleName', $moduleName);
        $this->assign('TableName', tableNameToModelName($tableName)); //修正为驼峰命名，首字母大写
        # 获取控制器模版代码
        $templateFilePath = MODULE_PATH . TPH_TEMPLATE_PATH . TPH_CONTROLLER_PATH . $controllerFileName;
        if ($methodFileName) {
            $templateFilePath = MODULE_PATH . TPH_TEMPLATE_PATH . TPH_CONTROLLER_PATH . TPH_METHOD_PATH . $methodFileName;
        }
        $resultCode = $this->fetch($templateFilePath);
        # END-获取控制器模版代码
        return $resultCode;
    }

    /**
     * 获取模型代码
     * @param $controllerFileName
     * @param null $methodFileName
     * @param null $tableName
     * @return string
     */
    public function getModelCode($modelFileName, $tableName = null, $moduleName=null)
    {
        $this->getCodeInit();
        $tableName = $tableName ? $tableName : I('table');
        $this->assign('tableName', columNameToVarName($tableName));
        $this->assign('moduleName', $moduleName);
        $this->assign('TableName', tableNameToModelName($tableName)); //修正为驼峰命名，首字母大写
        # 获取控制器模版代码
        $templateFilePath = MODULE_PATH . TPH_TEMPLATE_PATH . TPH_MODEL_PATH . $modelFileName;
        $resultCode = $this->fetch($templateFilePath);
        # END-获取控制器模版代码
        return $resultCode;
    }



    /**
     * 解析前台View模板
     * @param $templateFileName
     * @param $operateTitle
     * @param $content
     * @return mixed
     */
    public function getViewCode($templateFileName, $tableName = null)
    {
        $this->getCodeInit();
        $tableName = $tableName ? $tableName : I('table');
        $commonTemplateFilePath = MODULE_PATH . TPH_TEMPLATE_PATH . TPH_VIEW_PATH . $templateFileName;      // 通用模版路径
        $TableName = tableNameToModelName($tableName);
        $customTemplateFilePath = MODULE_PATH . TPH_TEMPLATE_PATH . TPH_VIEW_PATH . $TableName . '/' . $templateFileName;      // 定制模版路径
        $tableInfoArray = getTableInfoArray($tableName);
        $tableArray = getTableArray($tableName);
        $columnNameKey = getColumnNameKey();
        $columnCommentKey = getColumnCommentKey();
        # 填充内容
        $this->assign('tableName', $tableName);             // 原表名
        $this->assign('TableName', lcfirst($TableName));    // 小驼峰命名
        $this->assign('tableInfoArray', $tableInfoArray);
        $this->assign('tableArray', $tableArray);
        $this->assign('columnNameKey', $columnNameKey);
        $this->assign('columnCommentKey', $columnCommentKey);
        try{
            $fileContent = $this->fetch($customTemplateFilePath);
        }catch (\Exception $e){
            $fileContent = $this->fetch($commonTemplateFilePath);
        }
        return $fileContent;
    }

    /**
     * 获取代码初始化
     */
    private function getCodeInit(){
        if(!defined('IS_EXTEND'))
            define('IS_EXTEND', false);     // 模板继承
        if(!defined('IS_TEMPLATE_REPLACE'))
            define('IS_TEMPLATE_REPLACE', false);   // 模版替换
        if(!I('isTemplateInclude')&&!defined('IS_TEMPLATE_INCLUDE'))
            define('IS_TEMPLATE_INCLUDE', false);   // 包含文件
    }


    /**
     * 创建定制表单
     */
    public function createCustomForm(){
        $modelId = I('model_id');
        $modelId || $this->error('参数不能为空！');
        $this->getCodeInit();
        define('TPH_CUSTOM_FORM', false);  // 是否为定制表单
        // 获取当前的模型信息
        $model = get_document_model($modelId);
        $this->assign('model', $model);

        //获取表单字段排序
        $fields = get_model_attribute($model['id']);
        $this->assign('fields', $fields);
        $customFormContent = $this->fetch('Model/customForm');
        $moduleName = MODULE_NAME.'/'.TPH_TEMPLATE;
        $tableName = $model['name'];
        $customFormPath = getViewPath($moduleName, $tableName, 'edit');
        $result = FileUtil::writeFile($customFormPath, $customFormContent);
        if($result>0){
            $this->mtReturn(200, "创建定制表单成功!", $_REQUEST['navTabId'], false);    // 更新成功
        }
        $this->mtReturn(300, "创建定制表单失败!", $_REQUEST['navTabId'], false);    // 更新成功
    }



}